﻿using Dapper.Extensions;
using System;
using System.Collections.Generic;
using System.Web.Http;
using YouWei.Api.Common;
using YouWei.Api.Models;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Models;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace YouWei.Api.Controllers
{
    /// <summary>
    /// 群空间内容
    /// </summary>
    public class GroupCommentController : BaseApiController
    {
        private GroupCommentService _service = new GroupCommentService();
        private GroupCommentDetailService _serviceDetail = new GroupCommentDetailService();
        private GroupCommentImageService _serviceImg = new GroupCommentImageService();

        private WeChartTrailService _serviceTrail = new WeChartTrailService();
        private TrailCommentService _serviceTrailComment = new TrailCommentService();

        string imgUrl = ConfigHelper.GetAppSettingValue("FileUploadUrl");  //文件路径
        string imgListUrl = ConfigHelper.GetAppSettingValue("FileUploadYSUrl"); //文件压缩路径

        /// <summary>
        /// 获取内容列表（分页）
        /// </summary>
        /// <param name="PageSize">每页条数</param>
        /// <param name="PageIndex">页码</param>
        /// <param name="OpenID">openId,仅做记录日志使用，不做查询</param>
        /// <param name="Section">文章所属板块（1：随笔 2：游记 3.求助 4心情）</param>
        /// <param name="isHot">是否是热门推荐，1是0否</param>
        /// <param name="carGroupId">所属群组,0为不做筛选</param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<Page<GroupCommentDto>> GetCommentList(int PageSize, int PageIndex, string OpenID, int Section, int isHot, int carGroupId)
        {
            ResultData<Page<GroupCommentDto>> result = ResultData<Page<GroupCommentDto>>.Success();
            var commentData = _service.Pages(PageIndex, PageSize, OpenID, Section, isHot, carGroupId, "GroupCommentID", "DESC");
            var ids = "";
            if (commentData.rows.Count > 0)
            {
                foreach (var comment in commentData.rows)
                {
                    ids += comment.GroupCommentID;
                    ids += ",";
                    if (comment.HeadImgUrl != null && !comment.HeadImgUrl.StartsWith("http"))
                    {
                        comment.HeadImgUrl = imgListUrl + comment.HeadImgUrl;
                    }
                    if (comment.WxHeadImgUrl != null && !comment.WxHeadImgUrl.StartsWith("http"))
                    {
                        comment.WxHeadImgUrl = imgListUrl + comment.WxHeadImgUrl;
                    }
                }
                ids = ids.Substring(0, ids.Length - 1);
                List<GroupCommentImage> imgList = _serviceImg.PagesByCommentIDs(ids);

                foreach (var comment in commentData.rows)
                {
                    var list = new List<GroupCommentImage>();
                    foreach (var img in imgList)
                    {
                        if (img.GroupCommentID == comment.GroupCommentID)
                        {
                            if (img.ImageUrl != null && !img.ImageUrl.StartsWith("http"))
                            {
                                img.ImageUrl = imgListUrl + img.ImageUrl;
                            }
                            list.Add(img);
                        }
                    }
                    comment.CommentImgs = list;
                }
            }
            result.data = commentData;
            return result;
        }

        /// <summary>
        /// 获取内容信息
        /// </summary>
        /// <param name="CommentID"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<GroupCommentDto> GetCommentInfo(int CommentID)
        {
            ResultData<GroupCommentDto> result = ResultData<GroupCommentDto>.Error("未查询到内容信息");
            var data = _service.GetGroupCommentInfoById(CommentID);
            if (data.HeadImgUrl != null && !data.HeadImgUrl.StartsWith("http"))
            {
                data.HeadImgUrl = imgUrl + data.HeadImgUrl;
            }
            if (data.WxHeadImgUrl != null && !data.WxHeadImgUrl.StartsWith("http"))
            {
                data.WxHeadImgUrl = imgUrl + data.WxHeadImgUrl;
            }

            var imgList = _serviceImg.PagesByCommentID(CommentID);
            data.CommentImgs = imgList;
            foreach (var img in imgList)
            {
                if (img.ImageUrl != null && !img.ImageUrl.StartsWith("http"))
                {
                    img.ImageUrl = imgUrl + img.ImageUrl;
                }
            }

            if (data != null && data.IsActvie == 1)
            {
                result.status = 0;
                result.message = "查询成功";
                result.data = data;
            }
            return result;
        }

        /// <summary>
        /// 添加文章
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ResultData<int> AddComment(GroupCommentDto entity)
        {
            ResultData<int> result = new ResultData<int>();
            entity.CreateDate = DateTime.Now;
            entity.UpdateDate = DefultTime;
            entity.IsActvie = 1;
            entity.IsShow = 1;
            entity.IsHot = 1;
            if (string.IsNullOrEmpty(entity.CommentDesc))
            {
                if (!string.IsNullOrEmpty(entity.Detail))
                {
                    int lgh = entity.Detail.Length > 45 ? 45 : entity.Detail.Length;
                    entity.CommentDesc = entity.Detail.Substring(0, lgh);
                }
            }
            if (!string.IsNullOrEmpty(entity.HeadImgUrl))
            {
                entity.HeadImgUrl = entity.HeadImgUrl.Replace(imgUrl, "");
            }

            result.data = EConvert.ToInt(_service.Insert(entity));
            var dentity = new GroupCommentDetail()
            {
                GroupCommentID = result.data,
                CreateDate = DateTime.Now,
                Detail = entity.Detail,
                UpdateDate = DefultTime
            };
            _serviceDetail.Insert(dentity);

            if (entity.CommentImgs.Count > 0)
            {
                foreach (var item in entity.CommentImgs)
                {
                    item.ImageUrl = item.ImageUrl.Replace(imgUrl, "");
                    item.GroupCommentID = result.data;
                    item.CreateDate = DateTime.Now;
                    item.UpdateDate = DefultTime;
                    item.IsActvie = 1;
                }
                _serviceImg.Insert(entity.CommentImgs);
            }
            return result;
        }


        /// <summary>
        /// 更新内容
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public ResultData<string> UpdateComment(GroupCommentDto entity)
        {

            var result = ResultData<string>.Success("修改成功");
            if (entity.GroupCommentID <= 0)
            {
                result.status = -1;
                result.message = "缺少必要的参数ProductID";
                return result;
            }
            var model = _service.Single(entity.GroupCommentID);
            if (model == null)
            {
                result.status = -1;
                result.message = "修改失败，信息不存在";
                return result;
            }

            if (!string.IsNullOrEmpty(entity.HeadImgUrl))
            {
                entity.HeadImgUrl = entity.HeadImgUrl.Replace(imgUrl, "");
            }
            entity.CreateDate = model.CreateDate;
            entity.IsActvie = model.IsActvie;
            entity.UpdateDate = DateTime.Now;
            var r = _service.Update(entity);
            if (!r)
            {
                var dentity = new GroupCommentDetail()
                {
                    GroupCommentID = entity.GroupCommentID,
                    CreateDate = DateTime.Now,
                    Detail = entity.Detail,
                    UpdateDate = DateTime.Now
                };
                _serviceDetail.Update(dentity);
                result.status = -1;
                result.message = "修改失败";
            }
            return result;
        }

        /// <summary>
        /// 删除内容
        /// </summary>
        /// <param name="CommentID">主键ID</param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<string> DeleteComment([FromUri] int CommentID)
        {
            ResultData<string> result = ResultData<string>.Success("删除成功");
            if (CommentID <= 0)
            {
                result.status = -1;
                result.message = "删除内容失败，缺少必要的参数";
            }
            var model = _service.Single(CommentID);
            if (model != null)
            {
                model.IsActvie = 0;
                model.UpdateDate = DateTime.Now;
                var r = _service.Update(model);
                if (!r)
                {
                    result.status = -1;
                    result.message = "删除内容失败";
                }
            }
            return result;
        }

        /// <summary>
        /// 添加评论/留言
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost]
        public ResultData<int> AddTrailComment(TrailCommentParam param)
        {
            var result = ResultData<int>.Success("添加成功");
            _service.AddEvaluateCount(param.TrailIdentity);
            var entity = new TrailComment()
            {
                Comment = IllegalWordsSearch.Instance.Replace(param.Comment,'*'),
                TrailIdentity = param.TrailIdentity,
                UnionID = param.UnionID,
                UserID = param.UserID,
                OpenID = param.OpenID,
                CreateDate = DateTime.Now,
                IsShow = 0
            };
            var trailCommentId = EConvert.ToInt(_serviceTrailComment.Insert(entity));
            result.data = trailCommentId;
            return result;
        }

        /// <summary>
        /// 根据文章ID获取评论列表
        /// </summary>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <param name="CommentID"></param>
        /// <returns></returns>
        [HttpGet]
        public ResultData<Page<TrailCommentDto>> GetTrailCommentList(int PageIndex, int PageSize, int CommentID)
        {
            ResultData<Page<TrailCommentDto>> result = ResultData<Page<TrailCommentDto>>.Success();          
            result.data = _serviceTrailComment.Pages(PageIndex, PageSize, CommentID);
            foreach (var item in result.data.rows)
            {
                if (item.WxHeadImgUrl != null && !item.WxHeadImgUrl.StartsWith("http"))
                {
                    item.WxHeadImgUrl = imgUrl + item.WxHeadImgUrl;
                }
            }
            return result;
        }

    }
}
